﻿using GalaSoft.MvvmLight.Messaging;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using MVBuddy.Messages;
using MVBuddy.ViewModel;
using System;
using System.Windows;
using System.Windows.Controls.Primitives;

namespace MVBuddy.View
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            Messenger.Default.Register<LoginSuccessfulMessage>(this, LoginSuccessfulMessageReceived);
            Messenger.Default.Register<LoginFailedMessage>(this, LoginFailedMessageReceived);

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            Messenger.Default.Unregister<LoginSuccessfulMessage>(this, LoginSuccessfulMessageReceived);
            Messenger.Default.Unregister<LoginFailedMessage>(this, LoginFailedMessageReceived);

            base.OnNavigatedFrom(e);
        }

        private void Login_Click(object sender, System.EventArgs e)
        {
            SystemTray.ProgressIndicator.IsIndeterminate = true;
            SystemTray.ProgressIndicator.IsVisible = true;
            SystemTray.ProgressIndicator.Text = "Iniciando sesión...";

            Messenger.Default.Send<RequestLoginMessage>(new RequestLoginMessage());
        }

        private void LoginSuccessfulMessageReceived(LoginSuccessfulMessage message)
        {
            SystemTray.ProgressIndicator.IsVisible = false;

            NavigationService.Navigate(new Uri("/View/InfoPage.xaml", UriKind.Relative));
            NavigationService.RemoveBackEntry();
        }

        private void LoginFailedMessageReceived(LoginFailedMessage message)
        {
            SystemTray.ProgressIndicator.IsVisible = false;

            MessageBox.Show("Fallo al iniciar sesión. Introduce el usuario y contraseña correctos.");
        }
    }
}